<?php

namespace App\Models;

use DateTimeInterface;
use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    protected $appends = ['url'];

    protected $dateFormat = 'U';

    protected $fillable = [
        'title',
        'category_id',
        'tags',
        'content',
        'excerpt',
        'status',
        'show_comment',
        'is_original',
        'published_at',
        'deleted_at',
        'related_ids',
    ];

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

    public function getRelatedArticles()
    {
        return self::whereIn('id', explode(',', $this->related_ids))
            ->where('status', 1)
            ->select('id', 'title', 'published_at')
            ->orderByRaw('find_in_set(id, ?)', $this->related_ids)
            ->get();
    }

    public function getUrlAttribute()
    {
        if ($this->published_at) {
            return date('/Y/m/', $this->published_at) . $this->id . '.html';
        } else {
            return '';
        }
    }

    public function getPrev()
    {
        return self::where('status', 1)
            ->where('published_at', '<=', $this->published_at)
            ->where('id', '!=', $this->id)
            ->select('id', 'title', 'published_at')
            ->orderBy('published_at', 'desc')
            ->first();
    }

    public function getNext()
    {
        return self::where('status', 1)
            ->where('published_at', '>=', $this->published_at)
            ->where('id', '!=', $this->id)
            ->select('id', 'title', 'published_at')
            ->orderBy('published_at')
            ->first();
    }
}
